﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HPortal.Lib;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;

namespace HPortal.Backend
{
    public partial class EditChannel : System.Web.UI.Page
    {
        int channelID = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
        
            if (checkPermission() == false)
            {
                Response.Redirect("ChannelList.aspx");
            }

            channelID = int.Parse(HtmlHelper.GetRequestString("ChannelID", "0"));
            if (!IsPostBack)
            {
                BindgrvChannelRole(channelID);
                BindcboParent();

                if (channelID == 0)//Add New Channel
                {
                    this.cboParent.SelectedValue = "0";
                }
                else // Edit Channel
                {
                    int Priority = 0;
                    SqlDataReader dr = DatabaseHelper.SelectReader(null, "Channel", "ChannelID=" + channelID);
                    while (dr.Read())
                    {
                        txtChannelName.Text = dr["Name"].ToString();
                        txtUrl.Text = dr["Link"].ToString();
                        chkLock.Checked = (bool)dr["Locked"];
                        Priority = (int)dr["Priority"];
                        this.cboParent.SelectedValue = dr["ParentID"].ToString();
                        this.chkLang.SelectedIndex = int.Parse(dr["Language"].ToString());
                        this.chkApprove.Checked = Boolean.Parse(dr["RequireApprove"].ToString());
                    }
                    dr.Close();

                    ViewState["Priority"] = Priority;

                    int PriorityMax = DatabaseHelper.SelectScalarInt("Max(Priority)", "Channel", "ParentID=" + cboParent.SelectedValue);
                    int PriorityMin = DatabaseHelper.SelectScalarInt("Min(Priority)", "Channel", "ParentID=" + cboParent.SelectedValue);
                    this.imgDownChannel.Visible = Priority != PriorityMax;
                    this.imgUpChannel.Visible = Priority != PriorityMin;
                }
            }
        }
        private DataTable getChannel()
        {
            try
            {
                string where = string.Empty;
                if (this.Context.User.Identity.IsAuthenticated)
                {
                    string[] arrRoleName = Roles.GetRolesForUser(this.Context.User.Identity.Name);
                    foreach (string roleName in arrRoleName)
                    {
                        where += DatabaseHelper.EscapeQuoteUnicode(roleName) + ",";
                    }

                }
                where = where.Remove(where.Length - 1);
                where = "WHERE ChannelID IN (SELECT DISTINCT ChannelID FROM [ChannelRole] WHERE ([Role] IN (" + where + ") AND Administrated=1))";
                string query = "SELECT * FROM [Channel] " + where + " ORDER BY [ParentID],[Priority],[ChannelID]";
                return DatabaseHelper.Select(query);
            }
            catch
            {
                return null;
            }
        }
        private Boolean checkPermission()
        {
            try
            {
                string where = string.Empty;
                if (this.Context.User.Identity.IsAuthenticated)
                {
                    string[] arrRoleName = Roles.GetRolesForUser(this.Context.User.Identity.Name);
                    foreach (string roleName in arrRoleName)
                    {
                        where += DatabaseHelper.EscapeQuoteUnicode(roleName) + ",";
                    }

                }
                where = where.Remove(where.Length - 1);
                string query = "SELECT count(*) FROM [ChannelRole] WHERE ([Role] IN (" + where + ") AND Administrated=1)";
                if (int.Parse(DatabaseHelper.SelectScalar(query).ToString()) > 0)
                    return true;
                else
                    return false;
            }
            catch
            {
                return false; 
            }
        }
        protected void BindcboParent()
        {
            this.cboParent.DataSource = getChannel();
            this.cboParent.DataValueField = "ChannelID";
            this.cboParent.DataTextField = "Name";
            this.cboParent.DataBind();
            ListItem li = new ListItem("<Chuyên mục gốc>", "0");
            this.cboParent.Items.Add(li);
            this.cboParent.SelectedIndex = 0;
        }

        protected void BindgrvChannelRole(int channelID)
        {
            string[] arrRoles = Roles.GetAllRoles();
            grvChannelRole.DataSource = arrRoles;
            grvChannelRole.DataBind();

            SqlDataReader dr = DatabaseHelper.SelectReader(null, "ChannelRole", "ChannelID=" + channelID);
            while (dr.Read())
            {
                for (int i = 0; i < arrRoles.Length; i++)
                {
                    if (((Label)grvChannelRole.Rows[i].FindControl("lblRole")).Text == dr["Role"].ToString())
                    {
                        CheckBox chk = ((CheckBox)grvChannelRole.Rows[i].FindControl("chkViewed"));
                        chk.Checked = (bool)dr["Viewed"];
                        chk = ((CheckBox)grvChannelRole.Rows[i].FindControl("chkEdited"));
                        chk.Checked = (bool)dr["Edited"];
                        chk = ((CheckBox)grvChannelRole.Rows[i].FindControl("chkApproved"));
                        chk.Checked = (bool)dr["Approved"];
                        chk = ((CheckBox)grvChannelRole.Rows[i].FindControl("chkAdministrated"));
                        chk.Checked = (bool)dr["Administrated"];
                    }
                }
            }
            dr.Close();
        }
        protected void CheckedView(object sender, EventArgs e)
        {
            try
            {
                CheckBox chk = (CheckBox)sender;
                DatabaseHelper.Execute("EXEC editChannelRole " + channelID.ToString() + "," + DatabaseHelper.EscapeQuoteUnicode(chk.ToolTip) + "," + (chk.Checked ? "1" : "0") + ",null,null,null");
            }
            catch (Exception ex)
            {
                HtmlHelper.Alert(ex.Message, this.Page);
            }
        }
        protected void CheckedEdit(object sender, EventArgs e)
        {
            try
            {
                CheckBox chk = (CheckBox)sender;
                DatabaseHelper.Execute("EXEC editChannelRole " + channelID.ToString() + "," + DatabaseHelper.EscapeQuoteUnicode(chk.ToolTip) + ",null," + (chk.Checked ? "1" : "0") + ",null,null");
            }
            catch (Exception ex)
            {
                HtmlHelper.Alert(ex.Message, this.Page);
            }
        }
        protected void CheckedApprove(object sender, EventArgs e)
        {
            try
            {
                CheckBox chk = (CheckBox)sender;
                DatabaseHelper.Execute("EXEC editChannelRole " + channelID.ToString() + "," + DatabaseHelper.EscapeQuoteUnicode(chk.ToolTip) + ",null,null," + (chk.Checked ? "1" : "0") + ",null");
            }
            catch (Exception ex)
            {
                HtmlHelper.Alert(ex.Message, this.Page);
            }
        }

        protected void CheckedAdministrate(object sender, EventArgs e)
        {
            try
            {
                CheckBox chk = (CheckBox)sender;
                DatabaseHelper.Execute("EXEC editChannelRole " + channelID.ToString() + "," + DatabaseHelper.EscapeQuoteUnicode(chk.ToolTip) + ",null,null,null," + (chk.Checked ? "1" : "0"));
            }
            catch (Exception ex)
            {
                HtmlHelper.Alert(ex.Message, this.Page);
            }
        }
        protected void lblUpdate_Click(object sender, EventArgs e)
        {
            if (channelID != 0)	//UPDATE
                DatabaseHelper.Execute("UpdateChannel " + DatabaseHelper.EscapeQuoteUnicode(txtChannelName.Text) + "," + DatabaseHelper.EscapeQuote(txtUrl.Text) + "," + cboParent.SelectedValue + "," + (chkLock.Checked ? "1" : "0") + "," + chkLang.SelectedValue + "," + (chkApprove.Checked ? "1" : "0") + "," + channelID);
            else	//INSERT
            {
                int Priority = DatabaseHelper.SelectScalarInt("Max(Priority)", "Channel", "ParentID=" + cboParent.SelectedValue);
                Priority++;
                DatabaseHelper.Execute("InsertChannel " + DatabaseHelper.EscapeQuoteUnicode(txtChannelName.Text) + "," + DatabaseHelper.EscapeQuote(txtUrl.Text) + "," + cboParent.SelectedValue + "," + Priority.ToString() + "," + (chkLock.Checked?"1":"0") + "," + chkLang.SelectedValue + "," + (chkApprove.Checked?"1":"0"));
            }
            Response.Redirect("ChannelList.aspx");
        }

        protected void lblDelete_Click(object sender, EventArgs e)
        {
            try
            {
                DatabaseHelper.Execute("deleteChannel", new string[] {channelID.ToString() });
                Response.Redirect("ChannelList.aspx");
            }
            catch (Exception ex)
            {
                HtmlHelper.Alert(ex.Message, this.Page);
            }
        }
        protected void imgUpChannel_Click(object sender, ImageClickEventArgs e)
        {
            DatabaseHelper.Execute("UpChannel " + channelID);
            Response.Redirect("ChannelList.aspx");
        }
        protected void imgDownChannel_Click(object sender, ImageClickEventArgs e)
        {
            DatabaseHelper.Execute("DownChannel " + channelID);
            Response.Redirect("ChannelList.aspx");
        }
    }
}